package lion.se.lucene.search;

import java.util.ArrayList;
import java.util.List;

import lion.dev.lang.BeanUtil;
import lion.dev.lang.MapJ;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;

/**
 * @author Helin
 * @date 2011-4-2
 * 
 */
public class SearchResult {

	private int total = 0;
	private List<Document> documents = new ArrayList<Document>();
	private long time;

	public <T> List<T> list(Class<T> clazz) {

		List<T> result = new ArrayList<T>();

		for (Document doc : this.documents) {
			result.add(buildObject(clazz, doc));
		}
		return result;
	}

	public List<MapJ> docMaps() {

		List<MapJ> result = new ArrayList<MapJ>();

		MapJ mapJ = null;
		for (Document doc : this.documents) {
			mapJ = new MapJ();

			for (IndexableField field : doc.getFields()) {
				mapJ.put(field.name(), field.stringValue());
			}
			result.add(mapJ);
		}
		return result;

	}

	private <T> T buildObject(Class<T> clazz, Document doc) {

		T result = null;
		try {
			result = clazz.newInstance();
		} catch (Exception e) {
			return null;
		}
		MapJ param = new MapJ();
		for (IndexableField fields : doc.getFields()) {

			String name = fields.name();
			String val = doc.get(name);
			if (StringUtils.isEmpty(val)) {
				continue;
			}
			param.put(name, val);
		}
		BeanUtil.populate(result, param);

		return result;
	}

	public int getTotal() {

		return total;
	}

	public void setTotal(int total) {

		this.total = total;
	}

	public long getTime() {

		return time;
	}

	public void setTime(long time) {

		this.time = time;
	}

	public List<Document> getDocuments() {

		return documents;
	}
}
